<template>
	<div v-loading="loading" class="manage-coupon">
		<el-collapse-transition>
			<div v-show="!isShowDetail">
				<div class="top">
					<div class="app-main-top-box flexRBC">
						<div class="title">领券中心</div>
						<!--            <el-button type="primary" round size="medium" @click="openDialogOnShelf">上架合作伙伴的优惠券</el-button>-->
						<el-popover placement="right" width="400" trigger="click">
							<div v-loading="codeloading" class="wx-qrcode-popover">
								<div v-if="maInfo.DEFAULT.isOnline" class="wx-qrcode-box">
									<div v-if="qrCodeUrl" class="qr-code"><el-image :src="qrCodeUrl" /></div>
									<div v-if="maInfo.DEFAULT.auth" class="more-info">
										<div class="cell-item">
											<div>小程序原始ID：</div>
											<div>{{ maInfo.DEFAULT.auth.base.userName }}</div>
										</div>
										<div class="cell-item">
											<div>小程序APPID：</div>
											<div>{{ maInfo.DEFAULT.auth.base.appId }}</div>
										</div>
										<div class="cell-item">
											<div>小程序路径：</div>
											<div>sp-member/pages/couponCenter/main</div>
										</div>
									</div>
								</div>
								<div v-else class="err-tips">商户小程序未正式发布，暂时不可以获取二维码。</div>
							</div>
							<el-button slot="reference" type="primary" round size="medium" @click="openReceiveCenterQrCode">领券中心二维码</el-button>
						</el-popover>
					</div>
					<div class="tab">
						<el-tabs v-model="filterForm.upStatus" @tab-click="changeTab">
							<el-tab-pane label="已上架" name="1" />
							<el-tab-pane label="未上架" name="2" />
							<el-tab-pane label="已失效" name="3" />
						</el-tabs>
					</div>
				</div>

				<!-- 列表 -->
				<div class="content-main app-main-content-box">
					<!-- 筛选form-->
					<!--          <el-form ref="form" :model="filterForm" label-width="60px">
            <el-form-item label="筛选：">
              <el-radio-group v-model="filterForm.source" size="mini">
                <el-radio-button :label="1">全部</el-radio-button>
                <el-radio-button :label="2" >只看我的</el-radio-button>
                <el-radio-button :label="3" >只看合作伙伴的</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-form>-->
					<!--筛选-->
					<el-form ref="filterForm" :inline="true" :model="filterForm" label-width="70px" size="small">
						<el-form-item label="名称：" prop="couponName"><el-input v-model="filterForm.couponName" placeholder="请输入" clearable /></el-form-item>
						<el-form-item label="批次：" prop="stockId"><el-input v-model="filterForm.stockId" placeholder="请输入" clearable /></el-form-item>
						<el-form-item label="类型：" prop="types">
							<el-select
								v-model="filterForm.types"
								filterable
								multiple
								collapse-tags
								placeholder="请选择"
								class="w-400"
								@change="val => idsChange(val, 'couponType')"
							>
								<el-option label="所有类型" value />
								<el-option v-for="(v, k) in couponTypeOptions" :key="k" :label="v" :value="k" />
							</el-select>
						</el-form-item>
						<el-form-item label-width="0">
							<el-button type="primary" round @click="submitFilterForm">查 询</el-button>
							<el-button round @click="resetFilterForm">重 置</el-button>
						</el-form-item>
					</el-form>

					<div>
						<el-row v-if="list[filterForm.source].length > 0" :gutter="30" type="flex">
							<el-col v-for="(v, i) in list[filterForm.source]" :key="i" :xs="12" :sm="8" :md="8" :lg="8" :xl="6" class="coupon-card">
								<div v-if="v.couponTag == 1" class="coupon-labelType">商圈券</div>
								<el-card :body-style="{ padding: 0 }" shadow="hover">
									<div class="coupon-content">
										<div style="padding:20px 20px 10px">
											<div class="coupon-base">
												<div class="left">
													<img v-if="v.icon" :src="fileBaseUrl + v.icon" alt />
													<el-image v-else :src="'static/icon/coupon/i-coupon-' + v.couponType + '.png'" fit="fill" />
												</div>
												<div class="right">
													<div class="name app-line-one">{{ v.couponName }}</div>
													<div class="type app-line-one">批次号：{{ v.id }} | {{ couponTypeOptions[v.couponType] }}</div>
												</div>
											</div>
											<div class="coupon-detail">
												<div v-if="couponTypeGroup.cash.includes(v.couponType)" class="cash">{{ v.denomination / 100 }}元</div>
												<div v-if="couponTypeGroup.discount.includes(v.couponType)" class="discount">{{ v.discountPercent / 10 }}折</div>
												<div v-if="couponTypeGroup.exchange.includes(v.couponType)" class="exchange">{{ v.exchangeThings }}</div>
												<div v-if="couponTypeGroup.cash.includes(v.couponType)" class="describe">
													订单满{{ v.transactionMinimum / 100 }}元可用{{ v.maxUseNum && v.maxUseNum > 1 ? '，最多叠加' + v.maxUseNum + '张' : '' }}
												</div>
											</div>
											<div class="coupon-more">
												<div class="date">有效期：{{ v.startTime + ' ~ ' + v.endTime }}</div>
												<div class="belong">归属人：{{ `${v.belongMerchantName}（${v.belongMerchant}）` }}</div>
											</div>
										</div>
										<!--                    <div v-if="v.status===1" class="coupon-status">-->
										<!--                      <div v-if="!v.channelSync&&['cash_wx_busi','discount_wx_busi'].includes(v.couponType)&&v.syncMsg" class="app-text-color-danger">券渠道同步失败，请检查-->
										<!--                        <el-tooltip popper-class="el-tooltip-theme-fresh" placement="top" effect="light">-->
										<!--                          <div slot="content">-->
										<!--                            {{ v.syncMsg }}-->
										<!--                          </div>-->
										<!--                          <i class="el-icon-warning" />-->
										<!--                        </el-tooltip>-->
										<!--                      </div>-->
										<!--                      <div v-else-if="!v.channelSync&&['cash_wx_busi','discount_wx_busi'].includes(v.couponType)" class="app-text-color-warning">该批次需同步券渠道</div>-->
										<!--                      <div v-else class="app-text-color-primary">该批次激活即可使用</div>-->
										<!--                    </div>-->
										<div class="coupon-handle">
											<!--                      <el-button type="text" round size="small" @click="openDialogOnShelf">上架</el-button>-->
											<el-button v-if="filterForm.upStatus == 2" type="text" size="small" class="btn" @click="upShelf(v, i)">上架</el-button>
											<el-button v-if="filterForm.upStatus == 1" type="text" size="small" class="btn" @click="downShelf(v, i)">下架</el-button>
											<el-button type="text" size="small" class="btn" @click.native="showDetail(v)">详情</el-button>
										</div>
									</div>
								</el-card>
							</el-col>
						</el-row>
						<div v-else class="empty-text">暂无数据</div>
					</div>
				</div>
			</div>
		</el-collapse-transition>

		<!-- 效果详情 -->
		<el-collapse-transition><CouponInfo v-if="isShowDetail" ref="couponInfo" /></el-collapse-transition>

		<!-- 弹框 -->
		<DialogOnShelf ref="dialogOnShelf" />
	</div>
</template>

<script>
import CouponInfo from './components/CouponInfo';
import DialogOnShelf from './components/DialogOnShelf';
import { couponShelf, upCouponShelf, downCouponShelf, couponCenterQrCode } from '../../api/coupon';
import { mapActions, mapGetters } from 'vuex';

export default {
	components: {
		CouponInfo,
		DialogOnShelf
	},
	data() {
		return {
			// 配置
			couponTypeOptions: {
				cash: '代金券',
				cash_wx_pay: '微信支付代金券',
				cash_wx_busi: '微信商家代金券',
				discount: '折扣券',
				discount_wx_busi: '微信商家折扣券',
				exchange: '兑换券'
			},
			couponTypeGroup: {
				cash: ['cash', 'cash_wx_pay', 'cash_wx_busi'],
				discount: ['discount', 'discount_wx_busi'],
				exchange: ['exchange']
			},
			// 状态
			loading: false,
			codeloading: false,
			isShowDetail: false,
			// 数据
			list: {
				1: [],
				2: [],
				3: []
			}, // 列表
			qrCodeUrl: null,
			lastCouponTypesIds: [],
			couponTypesIds: ['', 'cash', 'cash_wx_pay', 'cash_wx_busi', 'discount', 'discount_wx_busi', 'exchange'],
			filterForm: {
				upStatus: '1',
				couponName: null,
				stockId: null,
				types: [],
				source: 1
			}
		};
	},
	computed: {
		...mapGetters(['maInfo'])
	},
	activated() {
		this.isShowDetail = false;
		this.fetchData();
		this.getActiveMaIsOnline();
	},
	created() {},
	mounted() {
		// this.fetchData()
		// this.getActiveMaIsOnline()
	},
	methods: {
		/**
		 *  获取数据
		 */
		// 获取小程序是否上线
		...mapActions(['getAuthMa']),
		getActiveMaIsOnline() {
			this.getAuthMa();
		},

		// 列表
		fetchData() {
			this.loading = true;
			const params = this.filterForm;
			couponShelf(params)
				.then(res => {
					console.log(res.data);
					this.list[1] = res.data.self.concat(res.data.others);
					this.list[2] = res.data.self || [];
					this.list[3] = res.data.others || [];
					console.log(this.list);
				})
				.catch(err => {})
				.finally(() => {
					this.loading = false;
				});
		},

		/**
		 * 按钮组
		 */
		// 打开合作商券
		// openDialogOnShelf() {
		//   this.$refs.dialogOnShelf.open(res => {})
		// },
		//  打开领券中心二维码
		openReceiveCenterQrCode() {
			this.codeloading = true;
			couponCenterQrCode()
				.then(res => {
					this.qrCodeUrl = res.data;
				})
				.finally(() => {
					this.codeloading = false;
				});
		},
		// 切换tab
		changeTab() {
			this.fetchData();
		},

		// 查询
		submitFilterForm() {
			this.fetchData(1);
		},

		// 重置
		resetFilterForm() {
			this.$refs.filterForm.resetFields();
			this.fetchData(1);
		},

		// 上架
		upShelf(row, index) {
			this.loading = true;
			upCouponShelf({ couponId: row.id })
				.then(res => {
					this.list[this.filterForm.source].splice(index, 1);
					this.$notify({
						title: '成功',
						message: '上架成功',
						type: 'success',
						duration: 2000,
						offset: 40
					});
				})
				.finally(() => {
					this.loading = false;
				});
		},

		// 下架
		downShelf(row, index) {
			this.loading = true;
			downCouponShelf({ couponId: row.id })
				.then(res => {
					this.list[this.filterForm.source].splice(index, 1);
					this.$notify({
						title: '成功',
						message: '下架成功',
						type: 'success',
						duration: 2000,
						offset: 40
					});
				})
				.finally(() => {
					this.loading = false;
				});
		},

		// 获取详情
		showDetail(row) {
			this.isShowDetail = true;
			this.$nextTick(() => {
				this.$refs.couponInfo.open(row).then(res => {
					this.fetchData();
					this.isShowDetail = false;
				});
			});
		},

		/**
		 * 状态组
		 */
		// 多选改变
		idsChange(val, type) {
			let lastIdsType = '';
			let idsType = '';
			let allIds = '';
			switch (type) {
				case 'couponType':
					lastIdsType = 'lastCouponTypesIds';
					idsType = 'types';
					allIds = 'couponTypesIds';
					break;
			}
			const lastVal = this[lastIdsType];
			if (val.includes('')) {
				this.filterForm[idsType] = this[allIds];
			}
			if (lastVal.includes('') && !val.includes('')) {
				this.filterForm[idsType] = [];
			}
			if (lastVal.includes('') && val.includes('')) {
				val.splice(val.findIndex(v => v === ''), 1);
				this.filterForm[idsType] = val;
			}
			if (!lastVal.includes('') && !val.includes('')) {
				if (val.length === this[allIds].length - 1) {
					this.filterForm[idsType] = [''].concat(val);
				}
			}
			this[lastIdsType] = this.filterForm[idsType];
		}
	}
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
/* tab */
::v-deep {
	.el-tabs__header {
		margin-bottom: 0;
		background-color: #fff;
		border-radius: 0 0 5px 5px;
	}

	.el-tabs__nav-wrap::after {
		background-color: #fff;
	}

	.el-tabs__active-bar {
		height: 4px;
	}

	.el-row {
		flex-wrap: wrap;
	}

	.el-card,
	.el-card__body {
		height: 100%;
	}
}

/*券二维码*/
.wx-qrcode-popover {
	display: flex;

	.wx-qrcode-box {
		width: 100%;
		.qr-code {
			margin: 0 auto 10px;
			width: 220px;
			height: 220px;
		}

		.more-info {
			display: flex;
			flex: 1;
			flex-direction: column;
			justify-content: center;
			font-size: 14px;

			.cell-item {
				display: flex;
				margin-bottom: 10px;

				div:first-child {
					flex: 0 0 120px;
					text-align: right;
				}

				div:last-child {
					flex: 1;
					color: #606266;
					word-break: break-all;
				}
			}
		}
	}

	.err-tips {
		text-align: center;
	}
}

/* 头部 */
.top {
	padding: 24px 30px 0;
	border-radius: 5px 5px;
	background-color: #fff;
	margin-bottom: 10px;

	.title {
		font-size: 20px;
	}
}

.empty-text {
	line-height: 60px;
	text-align: center;
	color: #909399;
	font-size: 14px;
}

/* 卡片 */
.coupon-card {
	margin-bottom: 20px;
	//height: 270px;
	cursor: pointer;
	position: relative;
	.coupon-labelType {
		position: absolute;
		top: 0;
		right: 15px;
		background-color: $primary;
		color: white;
		padding: 5px 10px;
	}
	.coupon-content {
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		height: 100%;
	}

	.coupon-base {
		display: flex;

		.left {
			overflow: hidden;
			flex: 0 0 auto;
			width: 80px;
			height: 80px;
			margin-right: 15px;
			border-radius: 50%;
			border: 1px solid #e7e7e7;
		}

		.right {
			flex: 1 1 auto;
			display: flex;
			flex-direction: column;
			justify-content: center;

			.name {
				font-size: 20px;
				// margin-top: 25px;
				font-weight: bold;
			}

			.type {
				margin-top: 5px;
				font-size: 14px;
				color: #909399;
			}
		}
	}

	.coupon-detail {
		text-align: center;
		border-bottom: 1px solid #e7e7e7;
		height: 90px;

		.cash,
		.discount,
		.exchange {
			font-size: 24px;
			margin-top: 10px;
			font-weight: bold;
		}

		.describe {
			margin-top: 10px;
			font-size: 14px;
			color: #909399;
		}
	}

	.coupon-more {
		margin-top: 10px;
		font-size: 14px;
		color: #909399;

		.date {
		}

		.belong {
		}
	}

	.coupon-status {
		margin-top: 10px;
		padding-top: 10px;
		border-top: 1px solid #e7e7e7;
		font-size: 14px;
	}

	.coupon-handle {
		display: flex;
		height: 40px;

		.btn {
			flex: 1;
			padding: 0;
			border-radius: 0;
			margin: 0;
			border-top: 1px solid #e7e7e7;
		}

		.btn + .btn {
			margin-left: 0;
		}

		.btn:not(:last-child) {
			border-right: 1px solid #e7e7e7;
		}
	}
}
</style>
